/**
 * 主页
 */
$(function() {
	initPage();// 初始化界面
});

layui.use([ "element", "layer" ], function() {
	var $ = layui.jquery;
	var layer = layui.layer;
	var element = layui.element;

	var tabNameList = new Array();
	tabNameList[0] = "首页";
	
	
	clinicEvent();// 门诊报表点击事件
	initBar(); //将侧拉条挡住
	
	function clinicEvent() {
		// 门诊报表点击事件
		$(".clinicReport").on("click", function() {
			if(isTabExist("门诊报表")) { //如果已经存在
				return;
			}
			layer.open({
				type : 2,
				title : '门诊报表',
				area : [ '400px', '300px' ],
				content : './views/clinicReportCondition.html', // iframe的url
				btn : [ "确认", "取消" ],
				btnAlign : 'c',
				scrollbar : false,
				resize : false,
				yes : function(index, layero) {
					// 获取弹出框页面中的变量param
					// $(layero).find("iframe")[0].contentWindow.param;
					// 弹出框调用页面中的函数getParam();
					$(layero).find("iframe")[0].contentWindow.initParam();
					layer.close(index);// 如果设定了yes回调，需进行手工关闭
					var tabName = $(".clinicReport").text();// 标签栏名称
					var tabHref = $(".clinicReport").find('input').val(); // 链接地址
					showIframe(tabName, tabHref);
				},
				cancel : function(index, layero) {
					layer.close(index);
				}
			});
		});
		// 科室报表点击事件
		$(".dpmReport").on("click", function() {
			if(isTabExist("科室报表")) { //如果已经存在
				return;
			}
			layer.open({
				type : 2,
				title : '科室报表',
				area : [ '400px', '300px' ],
				content : './views/dpmReportCondition.html', // iframe的url
				btn : [ "确认", "取消" ],
				btnAlign : 'c',
				scrollbar : false,
				resize : false,
				yes : function(index, layero) {
					// 获取弹出框页面中的变量param
					// $(layero).find("iframe")[0].contentWindow.param;

					// 弹出框调用页面中的函数initParam();
					$(layero).find("iframe")[0].contentWindow.initParam();
					layer.close(index);// 如果设定了yes回调，需进行手工关闭
					var tabName = $(".dpmReport").text();// 标签栏名称
					var tabHref = $(".dpmReport").find('input').val(); // 链接地址
					showIframe(tabName, tabHref);
				},
				cancel : function(index, layero) {
					layer.close(index);
				}
			});
		});
		// 费用项目报表点击事件
		$(".fundReport").on("click", function() {
			if(isTabExist("费用项目报表")) { //如果已经存在
				return;
			}
			layer.open({
				type : 2,
				title : '费用项目报表',
				area : [ '400px', '300px' ],
				content : './views/clinicFundReportCondition.html', // iframe的url
				btn : [ "确认", "取消" ],
				btnAlign : 'c',
				scrollbar : false,
				resize : false,
				yes : function(index, layero) {
					// 获取弹出框页面中的变量param
					// $(layero).find("iframe")[0].contentWindow.param;

					// 弹出框调用页面中的函数initParam();
					$(layero).find("iframe")[0].contentWindow.initParam();
					layer.close(index);// 如果设定了yes回调，需进行手工关闭
					var tabName = $(".fundReport").text();// 标签栏名称
					var tabHref = $(".fundReport").find('input').val(); // 链接地址
					showIframe(tabName, tabHref);
				},
				cancel : function(index, layero) {
					layer.close(index);
				}
			});
		});
		
		// 治疗单据点击事件
		$(".createTreatBill").on("click",function() {
			if(isTabExist("治疗单据")) { //如果已经存在
				return;
			}
			//importBill_category 1:表示治疗单据  2:费用单据
			localStorage.setItem("importBill_category", 1);
			layer.open({
				type : 2,
				title : '治疗单据所属信息',
				area : [ '530px', '495px' ],
				content : './views/billManager/billCondition.html', // iframe的url
				btn : [ "确认", "取消" ],
				btnAlign : 'r',
				scrollbar : false,
				resize : true,
				yes : function(index, layero) {
					// 获取弹出框页面中的变量param
					// $(layero).find("iframe")[0].contentWindow.param;
					// 弹出框调用页面中的函数initParam();获取治疗单据所属信息
					var data = $(layero).find("iframe")[0].contentWindow.initParam();
					console.log("index.js/importBill.data");
					console.log(data);
					if(data.clientId == "") {
						layer.msg("所属病人为空", {icon : 2,time : 1000,});
						return;
					}
					if(data.doctorId == "") {
						layer.msg("所属医生为空", {icon : 2,time : 1000,});
						return;
					}
					localStorage.setItem("importTreatBillParam", JSON.stringify(data));
					layer.close(index);// 如果设定了yes回调，需进行手工关闭
					var tabName = $(".createTreatBill").text();// 标签栏名称
					var tabHref = $(".createTreatBill").find('input').val(); // 链接地址
					showIframe(tabName, tabHref);
				},
				cancel : function(index, layero) {
					layer.close(index);
				}
			});
		});
		
		// 治疗信息点击事件
		$(".createTreatInfo").on("click",function() {
			if(isTabExist("治疗信息")) { //如果已经存在
				return;
			}
			layer.open({
				type : 2,
				title : '录入治疗信息',
				area : [ '530px', '495px' ],
				content : './views/treatInfoManager/treatInfoCondition.html', // iframe的url
				btn : [ "确认", "取消" ],
				btnAlign : 'r',
				scrollbar : false,
				resize : true,
				yes : function(index, layero) {
					// 获取弹出框页面中的变量param
					// $(layero).find("iframe")[0].contentWindow.param;
					// 弹出框调用页面中的函数initParam();获取治疗单据所属信息
					var data = $(layero).find("iframe")[0].contentWindow.initParam();
					console.log("index.js/createTreatInfo.data");
					console.log(data);
					if(data.clientId == "") {
						layer.msg("所属病人为空", {icon : 2,time : 1000,});
						return;
					}
					localStorage.setItem("medicalCardClientId", JSON.stringify(data));
					var tabName = $(".createTreatInfo").text();// 标签栏名称
					var tabHref = $(".createTreatInfo").find('input').val(); // 链接地址
					showIframe(tabName, tabHref);
					layer.close(index);// 如果设定了yes回调，需进行手工关闭
				},
				cancel : function(index, layero) {
					layer.close(index);
				}
			});
		});
		
		//治疗单据查看事件
		$(".checkTreatBill").on("click",function(){
			if(isTabExist("单据查看")){
				return;
			}
			layer.open({
				type : 2,
				title : '单据查看',
				area : ['350px','450px'],
				content : ['./views/billManager/billTableCondition.html','no'],
				btn : ["确认","取消"],
				yes : function(index,layero){
					var iframe = window[layero.find('iframe')[0]['name']];
					var isSuccess = iframe.submit();
					if(isSuccess == 1){
						layer.close(index);
						var tabName = $(".checkTreatBill").text();// 标签栏名称
						var tabHref = $(".checkTreatBill").find('input').val(); // 链接地址
						showIframe(tabName, tabHref);
					}
				}
			});
		});
		
		// 登出按钮点击事件
		$("#logout").on("click", function() {
			layer.open({
				type : 1,
				title : '确认退出?',
				btn : [ "确认", "取消" ],
				yes : function(index, layero) {
					$.ajax({
						type : "post",
						url : "./loginController/logout",
						success : function(response) {
							layer.close(index);// 如果设定了yes回调，需进行手工关闭
							localStorage.clear();
							window.location.href = "./login.html";
						}
					});
				},
				cancel : function(index, layero) {
					layer.close(index);
				}
			});
		});
		
		//基本资料点击事件
		$("#employeeData").on("click",function(){
			var employeeData = JSON.parse(localStorage.getItem("loginUser"));
			var code = employeeData.employeeCode;
			var name = employeeData.employeeName;
			var age = employeeData.employeeAge;
			var sex = employeeData.employeeSex;
			if(sex == 0){
				sex="男";
			}else if(sex == 1){
				sex="女";
			}
			var department = employeeData.departmentName;
			var position = employeeData.positionName;
			var loginTime = employeeData.loginTime;
			layer.msg("<ul><li>工号："+code+"</li><li>姓名："+name+"</li><li>年龄："+age+"</li><li>性别："+sex+"</li><li>所属科室："+department+"</li><li>职位："+position+"</li><li>最近登录时间："+loginTime+"</li></ul>",{
				time : false,
				btn : ['确定'],
				btnAlign : 'c'
			});
		});
		
		//修改密码点击事件
		$('#updatePassword').on('click',function(){
			layer.open({
				type : 1,
				title : "修改密码",
				skin : 'demo-class',
				area : ['350px','300px'],
				content : $('#udPwd'),
				btn : ['确定','取消'],
				yes : function(index,layero){  //点击确定时请求后台数据，查看密码是否正确
					var employeeId=JSON.parse(localStorage.getItem("loginUser")).employeeId;
					var oldPwd=$('input[name="oldPassword"]').val();
					employeeId={
						"employeeId" : employeeId,
						"oldPwd" : oldPwd
					};
					$.ajax({
						data : employeeId,
						type : 'POST',
						url : './userController/employeeFindById',
						success : function(result){
							var employeeData = result.result;
							if(result.code == 200){		//旧密码正确
								layer.close(index);		//关闭第一个弹窗
								$('input[name="oldPassword"]').val("");
								layer.open({		    //弹出第二个窗口
									type : 1,
									title : "修改密码",
									skin : 'demo-class',
									area : ['350px','300px'],
									content : $('#udPwd2'),
									btn : ['修改','取消'],
									yes : function(index,layero){  //点击修改时，
										updatePwd(index);
									}
								});
								$('.layui-layer').css({'border-radius':'20px'});
							}else if(result.code == 400){
								layer.msg("密码错误");
							}
						}
					});
				}
			});
			$('.layui-layer').css({'border-radius':'20px'});
		});
		
		$('.clickListen').click(function() {
			var tabName = $(this).text();// 标签栏名称
			var tabHref = $(this).find('input').val(); // 链接地址
			showIframe(tabName, tabHref);

		});
		// 标签栏切换事件
		element.on('tab(tabList)', function(data) {
			var name = data.elem.find('ul').find('li').eq(data.index).text();
			var tabnamesize = name.length;
			var tabname = name.substring(0, tabnamesize - 1);
			iframeList = $('.iframes').find('Iframe');
			for (var i = 0; i < iframeList.length; i++) {
				if (tabname == $('.iframe').eq(i).attr('name')) {
					$('.iframes').find('Iframe').removeClass('layui-show');
					$('.iframe').eq(i).addClass('layui-show');
				}
			}
		});
		// 标签栏删除事件
		element.on('tabDelete(tabList)', function(data) {
			tabNameList.splice(data.index, 1);
			if (tabNameList.length == 0) {
				tabNameList[0] = "首页";
				element.tabAdd('tabList', {
					title : "首页",
					content : '',
					id : "首页"
				});
				element.tabChange('tabList', "首页");
				$('.iframe').eq(0).addClass('layui-show');
			}
		});
	}
	
	//判断Tab是否已经存在;true:存在,false:不存在
	function isTabExist(tabName) {
		//console.log("index.js/isTabExist.tabName");
		//console.log(tabName);
		for (var i = 0; i < tabNameList.length; i++) {
			if (tabNameList[i] == tabName) {
				$('.iframes').find('Iframe').removeClass('layui-show');
				var iframeList = new Array();
				iframeList = $('.iframes').find('Iframe');
				for (var i = 0; i < iframeList.length; i++) {
					if (tabName == $('.iframe').eq(i).attr('name')) {
						$('.iframe').eq(i).addClass('layui-show');
					}
				}
				element.tabChange('tabList', tabName);
				return true;
			}
		}
		return false;
	}
	
	function showIframe(tabName, tabHref) {
		var tabNameListsize = tabNameList.length;// 标签栏长度
		var isExist = 0; // (0:新标签,1:旧标签)
		if (tabName.indexOf('首页')>=0){
			tabName='首页';
		}
		for (var i = 0; i < tabNameListsize; i++) {
			if (tabNameList[i] != tabName) {
				isExist = 1;
			} else {
				isExist = 0;
				break;
			}
		}
		if (isExist == 1) {
			// 如果是新标签
			tabNameList.push(tabName);
			element.tabAdd('tabList', {
				title : tabName,
				content : '',
				id : tabName
			});
			$('.iframes').find('Iframe').removeClass('layui-show');
			$('.iframes').append(
					"<Iframe name=" + tabName + " class=" + "iframe" + " src=" + "./" + tabHref
							+ "" + " scrolling=" + "yes" + " frameborder=" + "0" + "></iframe> ");
			var iframeList = new Array();
			iframeList = $('.iframes').find('Iframe');
			for (var i = 0; i < iframeList.length; i++) {
				if (tabName == $('.iframe').eq(i).attr('name')) {
					$('.iframe').eq(i).addClass('layui-tab-item');
					$('.iframe').eq(i).addClass('layui-show');
				}
			}
			element.tabChange('tabList', tabName);
			return;
		}

		// 如果是旧标签
		$('.iframes').find('Iframe').removeClass('layui-show');
		var iframeList = new Array();
		iframeList = $('.iframes').find('Iframe');
		for (var i = 0; i < iframeList.length; i++) {
			if (tabName == $('.iframe').eq(i).attr('name')) {
				$('.iframe').eq(i).addClass('layui-show');
			}
		}
		element.tabChange('tabList', tabName);
	}
});

//将侧拉条挡住
function initBar() {
	var leftWidth = (window.innerWidth * 0.12 +40) + 'px';
	$('.littleleftFrame').css({
		'width' : leftWidth
	});
	$(window).resize(function() {
		var leftWidth = (window.innerWidth * 0.12 + 40) + 'px';
		$('.littleleftFrame').css({
			'width' : leftWidth
		});
	});
	
	$('.layui-nav-more').css({
		'right' : "30px"
	});
	
	$(".layui-nav-more").eq(3).css({"right":"0"});
}

// 初始化界面
function initPage() {
	var userInfo = JSON.parse(localStorage.getItem("loginUser"));
	//console.log(userInfo.permission);
	$("#userName").html("您好！"+userInfo.employeeName);
	var sex=userInfo.employeeSex;
	if(sex == 0){
		$('#headImg').attr('src','./resources/img/man.png');
	}else if(sex == 1){
		$('#headImg').attr('src','./resources/img/girl.png');
	}
	//报表权限
	if(userInfo.permission.getReport < 2) {
		$("#report_li").hide();
		//$("#clinicReport_dd").hide();
		//$("#dpmReport_dd").hide();
		//$("#fundReport_dd").hide();
	}else if(userInfo.permission.getReport == 2) {
		$("#clinicReport_dd").hide();
		$("#dpmReport_dd").show();
		$("#fundReport_dd").hide();
	}else if(userInfo.permission.getReport > 2){
		$("#clinicReport_dd").show();
		$("#dpmReport_dd").show();
		$("#fundReport_dd").show();
		
	}
	//单据权限
	if(userInfo.permission.createTreatBill == 0 && userInfo.permission.createTreatBillPerson == 0){
		$("#createTreatBill_dd").hide();
	}
	if(userInfo.permission.createFundBill == 0){
		$("#createFundBill_dd").hide();
	}
	if(userInfo.permission.createFundBill == 0 && userInfo.permission.createTreatBill == 0) {
		$("#createBill_li").hide();
	}
}

//修改密码
function updatePwd(index){		
	var newPassword = $('input[name="newPassword"]').val();
	var newPassword2 = $('input[name="newPassword2"]').val();
	var employeeId2=JSON.parse(localStorage.getItem("loginUser")).employeeId;
	if(newPassword == newPassword2){	//判断两次密码是否一致
		newPassword={
			"employeeId" : employeeId2,
			"newPassword" : newPassword
		};
		$.ajax({
			data : newPassword,
			type : 'POST',
			url : './userController/updateEmployeePwd',
			success : function(result){
				if(result.code == 200){
					layer.msg("修改成功");
					$("input[name='newPassword']").val("");
					$("input[name='newPassword2']").val("");
					layer.close(index);
				}else{
					layer.msg("修改失败");
				}
			}
		});
	}else{
		layer.msg("密码不一致");
	}
}